package cn.trigram.validation.annotation.validator;

import cn.trigram.date.DateUtil;
import cn.trigram.validation.annotation.DateFormatCheck;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import javax.validation.ConstraintValidatorContext;

/**
 * 字符日期时间格式校验器
 *
 * @version 1.0.0
 * @date 2022/08/04 09:11:06
 * @since 1.0.0
 */
public abstract class AbstractDateFormatValidator {
    protected DateFormatCheck dateFormatCheck;
    protected DateTimeFormatter formatter;

    public void initialize(DateFormatCheck dateFormatCheck) {
        this.dateFormatCheck = dateFormatCheck;
        this.formatter = DateUtil.formatter(dateFormatCheck.value());
    }

    public boolean isValid(String value, ConstraintValidatorContext context) {
        boolean isValid;
        try {
            this.formatter.parse(value);
            isValid = true;
        } catch (DateTimeParseException e) {
            isValid = false;
        }
        return isValid;
    }
}